<script setup>
import { ref,reactive, nextTick,onActivated,getCurrentInstance,onMounted, watch  } from 'vue'; 
import { useRoute,useRouter } from 'vue-router';
import { ElMessage,ElMessageBox  } from 'element-plus';
import { getBaseSetting,editBaseSetting,getAllCommodityExtraAttributes,changeAllCommodityExtraAttributes,editCommodityExtraAttributes,queryNameAndQuantity } from '@/api/ShopDatabase/goodsSetting.js'
import getRules from "@/validUtils";
import DiaSetting from './components/DiaSetting.vue'

const activeName = ref('good');

const seachTable = ref(null);
const route = useRoute();
const router = useRouter();
const instance = getCurrentInstance();
const attrLoading = ref(false);
const attrTitle = ref("")
const formInline = ref([
])

const btnLefts = ref([
])
const btnRights = ref([
])

const tableConfig = ref([
    {
      prop: "attributeValue",
      label: "属性名称",
      width:100,
    },
    {
      prop: "description",
      label: "描述"
    },
    {
      prop: "secondConfigVOs",
      label: "属性值",
      format:(value)=>{
        if(!value.length) return ''
        return value.filter(item=>item.delFlag===0).map(item=>item.attributeValue).join('、')
      }
    },
    {
      type: "action",
      label: "操作",
      width: 100,
      btns: [
        {
          label: () => "编辑",
          type:"success",
          click: async (row) => {
            attrList.value = [
                {
                    value:"",
                    delFlag:0,
                }
            ];
            attrList.value= row.secondConfigVOs.map((lis)=>{
                return {
                    ...lis,
                    value:lis.attributeValue,
                    delFlag:+(lis?.delFlag || 0)
                }
            })
            console.log(row,222);
            attrId.value = row.id;
            attrTitle.value = `编辑${ row.attributeValue }的属性值`;
            attrFlag.value = true;
          },
        },
      ],
    },
]);
const tableLoading = ref(false)

const tableData = ref([]);


const handlerSearch = async (formInline)=>{
    tableLoading.value = true;
    try{
        const result = await getBaseSetting();
        tableData.value = result;
    }catch(e){
    }finally{
        tableLoading.value = false;
    }
}
const attrList = ref([{
    value:"",
    delFlag:0,
}])
const attrId = ref("");
const attrFlag = ref(false);
const isExceedLimitLoading = ref(false);
const isExceedLimit = async (params)=>{
    try{
        isExceedLimitLoading.value = true
        const res = await queryNameAndQuantity(params)
        if(res.repeatFlag){
            ElMessage.error("该属性名称已存在,请重新输入")
            return false
        }
        if(res.quantity){
            ElMessage.error("数量已超过100")
            return false
        }
        return true
    }finally{
        isExceedLimitLoading.value = false
    }
}
const handleAttrBlur = async (index)=>{
    const params = {
        id:attrList.value[index].id,
        parentId:attrId.value,
        attributeValue:attrList.value[index].value
    }
    if(!await isExceedLimit(params)){
        attrList.value[index].value = ''
    }
}
const increHandle = async ()=>{
    const params = {
        parentId:attrId.value,
    }
    if(!await isExceedLimit(params)) return
    attrList.value.push({
        value:"",
        delFlag:0,
    });
}
const diffHandle = (index)=>{
    attrList.value.splice(index,1);
}
const confrimAttr = async ()=>{
    let flag = false;
    attrList.value.forEach(lis=>{
        if((lis.value??'') === ''){
            flag = true;
        }
    })
    if(flag){
        ElMessage.error("属性值不能为空");
        return;
    }
    attrLoading.value = true;
    try{
        const params = attrList.value.map(item => {
            return {
                ...item,
                attributeValue:item.value,
                parentId:item.parentId ? item.parentId : attrId.value,
            }
        })
        await editBaseSetting({secondConfigQoList:params});
        attrFlag.value = false;
        handlerSearch();
    }catch(e){

    }finally{
        attrLoading.value = false;
    }
}

//自定义属性设置
const attrCustomFlag = ref(false);
const attrCustomLoading = ref(false);
const attrCustomForm = ref({
    type:1,
    name:"",
    selectType:1,
    selectValue:[{
        value:""
    }],
    sourceType:1

})
const attrCustomFormRef = ref(null);
const rules = reactive({

})
const increCustomHandle = ()=>{
    attrCustomForm.value.selectValue.push({
        value:""
    });
}
const diffCustomHandle = (index)=>{
    attrCustomForm.value.selectValue.splice(index,1);
}
const checkRepeat = (index,value)=>{

    let flag = -1;
    attrCustomForm.value.selectValue.forEach((lis,i)=>{
        console.log(lis.value,index,i,value);
        if((lis.value !=='') && (index != i) && (lis.value == value)){
  
            flag = i
        }
    })
    if(flag != -1){
        ElMessage.error('选项值不能重复');
        attrCustomForm.value.selectValue[index].value = "";
    }
}
const insertCustomLoading = ref(false);
const confrimCustomAttr = ()=>{

    attrCustomFormRef.value.validate(async (valid, fields) => {
        if (valid) {
            if(attrCustomForm.value.type == 3){
                let flag = false;
                attrCustomForm.value.selectValue.forEach(lis=>{
                    console.log(lis,2222);
                    if((lis.value??'') === ''){
                        flag = true;
                    }
                })
                if(flag){
                    ElMessage.error("选项内容不能为空");
                    return;
                }
            }
            let fieldType = attrCustomForm.value.type;
            if(attrCustomForm.value.type == 3){
                if(attrCustomForm.value.selectType == 1){
                    fieldType = 3;
                }else{
                    fieldType = 4;
                }
            }

            let optionContent = attrCustomForm.value.selectValue.map(lis=>lis.value).join(',')

            let params = {
                fieldType:fieldType,
                fieldName:attrCustomForm.value.name,
                sourceType:attrCustomForm.value.sourceType,
                optionContent:optionContent
            }
            if((attrCustomForm.value.id??'') !== ''){
                params.id = attrCustomForm.value.id;
            }
            insertCustomLoading.value = true;
            try{
                await editCommodityExtraAttributes(params);
                ElMessage.success('新增成功');
                attrCustomFlag.value = false;
                _getAllCommodityExtraAttributes();
            }catch(e){

            }finally{
                insertCustomLoading.value = false
            }
        }
    })
}
const addCustomAttr = (sourceType)=>{
    attrCustomFlag.value = true;
    attrCustomForm.value = {
        type:1,
        name:"",
        selectType:1,
        selectValue:[{
            value:""
        }],
        sourceType:sourceType
    }
}
const editCustomAttr = (row)=>{
    attrCustomFlag.value = true;
    console.log(row,222);
    attrCustomForm.value = {
        type:Number(row.fieldType),
        name:row.fieldName,
        selectType:1,
        selectValue:[{
            value:""
        }],
        sourceType:row.sourceType,
        id:row.id
    }
    if(attrCustomForm.value.type == 3){
        attrCustomForm.value.type = 3;
        attrCustomForm.value.selectType = 1;
    }
    if(attrCustomForm.value.type == 4){
        
        attrCustomForm.value.type = 3;
        attrCustomForm.value.selectType = 2;
        console.log(attrCustomForm.value,666);
    }   
    
    if((row.optionContent??'') !==''){
        let selectValue = row.optionContent.split(',');
        attrCustomForm.value.selectValue = selectValue.map(lis=>{
            return {
                value:lis
            }
        })
    }

}

const customData = ref([]);
const changeStatus = (row,fieldName,index)=>{

    ElMessageBox(
        {
            confirmButtonText: row.disabled?'启用':'禁用',
            cancelButtonText: '取消',
            type: row.disabled?"warning":'error',
            title: '提示',
            showCancelButton: true,
            message:`确定${ row.disabled?'启用':'禁用' }该自定义属性？`,
            confirmButtonClass:row.disabled?"el-button--success":"el-button--danger",
            beforeClose: async (action, instance, done) => {
                if (action === 'confirm') {
                    let params = {
                        id: row.id,
                        disabled: row.disabled?0:1
                    }
                    await changeAllCommodityExtraAttributes(params);
                    _getAllCommodityExtraAttributes();
                    done()
                } else {
                    customData.value[fieldName][index].disabled = row.oldDisabled;
                    done()
                }
            },
        }
    )
}
const changeTab = (tabName)=>{
    if(tabName == 'custom'){
        _getAllCommodityExtraAttributes();
    }
}
const _getAllCommodityExtraAttributes = async ()=>{
    attrCustomLoading.value = true;
    try{
        let result = await getAllCommodityExtraAttributes();
        customData.value = result;
        for (const key in customData.value) {

            if (Object.hasOwnProperty.call(customData.value, key)) {
                customData.value[key].map(lis=>{
                    let { disabled,fieldType } = lis;
                    lis.disabled =  disabled == 1?false:true;
                    lis.oldDisabled = disabled == 1?false:true;
                    lis.fieldTypeName = ["","文本","数值","单选","多选"][fieldType];
                })
            }
        }
        console.log(customData.value,222);
    }catch(e){

    }finally{
        attrCustomLoading.value = false;
    }
}
</script>
<template>
    <div class="page-contain">
        <el-tabs v-model="activeName" class="demo-tabs" @tab-change="changeTab">
            <el-tab-pane label="商品基础设置" name="good">

                <SeachTable 
                    v-if="activeName == 'good'"
                    style="padding-bottom:12px"
                    :tableType="1"
                    ref="seachTable"
                    :forms="formInline"
                    :btnLefts="btnLefts"
                    :btnRights="btnRights"
                    :tableLoading="tableLoading"
                    :tableConfig="tableConfig"
                    :tableData="tableData"
                    @handlerSearch="handlerSearch"
                    :showBtn="false"
                    :showLine="false"
                    :isShowPage="false"
                    :showJg="false"
                >

                </SeachTable>
            </el-tab-pane>
            <el-tab-pane label="自定义属性设置" name="custom">
                <div class="tab-pag" v-loading="attrCustomLoading" v-if="activeName == 'custom'">
                    <div style="width:100%;margin-bottom:24px">
                        <div class="lis-head">
                            <div class="icon-view">
                                <div class="icon-view-on"></div>
                            </div>
                            <span class="label-name">产品自定义属性</span>
                            <el-button plain type="primary" @click="addCustomAttr(1)">
                                <img src="@/assets/icon/btn-add-blue.png" alt="" style="margin-right:8px;width:14px;height:14px">
                                添加属性
                            </el-button>
                        </div>
                        <el-table :data="customData.productAttributesList" style="width: 100%" stripe>
                            <el-table-column prop="fieldName" label="属性名称">
                            </el-table-column>
                            <el-table-column prop="fieldTypeName" label="类型">

                            </el-table-column>
                            <el-table-column prop="disabled" label="状态">
                                <template #default="scoped">
                                    <el-switch v-model="scoped.row.disabled" @change="changeStatus(scoped.row,'productAttributesList',scoped.$index)"/>
                                </template>
                            </el-table-column>
                            <el-table-column label="操作" fixed="right" width="120">
                                <template #default="scoped">
                                    <el-button type="success" plain size="small" @click="editCustomAttr(scoped.row)">
                                        编辑
                                    </el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                    </div>
                    <div style="width:100%;margin-bottom:24px">
                        <div class="lis-head">
                            <div class="icon-view">
                                <div class="icon-view-on"></div>
                            </div>
                            <span class="label-name">项目自定义属性</span>
                            <el-button plain type="primary" @click="addCustomAttr(2)">
                                <img src="@/assets/icon/btn-add-blue.png" alt="" style="margin-right:8px;width:14px;height:14px">
                                添加属性
                            </el-button>
                        </div>
                        <el-table :data="customData.projectAttributesList" style="width: 100%" stripe>
                            <el-table-column prop="fieldName" label="属性名称">
                            </el-table-column>
                            <el-table-column prop="fieldTypeName" label="类型">

                            </el-table-column>
                            <el-table-column prop="disabled" label="状态">
                                <template #default="scoped">
                                    <el-switch v-model="scoped.row.disabled" @change="changeStatus(scoped.row,'projectAttributesList',scoped.$index)"/>
                                </template>
                            </el-table-column>
                            <el-table-column label="操作" fixed="right" width="120">
                                <template #default="scoped">
                                    <el-button type="success" plain size="small" @click="editCustomAttr(scoped.row)">
                                        编辑
                                    </el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                    </div>
                    <div style="width:100%;margin-bottom:24px">
                        <div class="lis-head">
                            <div class="icon-view">
                                <div class="icon-view-on"></div>
                            </div>
                            <span class="label-name">套餐自定义属性</span>
                            <el-button plain type="primary" @click="addCustomAttr(3)">
                                <img src="@/assets/icon/btn-add-blue.png" alt="" style="margin-right:8px;width:14px;height:14px">
                                添加属性
                            </el-button>
                        </div>
                        <el-table :data="customData.comboAttributesList" style="width: 100%" stripe>
                            <el-table-column prop="fieldName" label="属性名称">
                            </el-table-column>
                            <el-table-column prop="fieldTypeName" label="类型">

                            </el-table-column>
                            <el-table-column prop="disabled" label="状态">
                                <template #default="scoped">
                                    <el-switch v-model="scoped.row.disabled" @change="changeStatus(scoped.row,'comboAttributesList',scoped.$index)"/>
                                </template>
                            </el-table-column>
                            <el-table-column label="操作" fixed="right" width="120">
                                <template #default="scoped">
                                    <el-button type="success" plain size="small" @click="editCustomAttr(scoped.row)">
                                        编辑
                                    </el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                    </div>
                    <div style="width:100%;margin-bottom:24px">
                        <div class="lis-head">
                            <div class="icon-view">
                                <div class="icon-view-on"></div>
                            </div>
                            <span class="label-name">疗程自定义属性</span>
                            <el-button plain type="primary" @click="addCustomAttr(7)">
                                <img src="@/assets/icon/btn-add-blue.png" alt="" style="margin-right:8px;width:14px;height:14px">
                                添加属性
                            </el-button>
                        </div>
                        <el-table :data="customData.courseAttributesList" style="width: 100%" stripe>
                            <el-table-column prop="fieldName" label="属性名称">
                            </el-table-column>
                            <el-table-column prop="fieldTypeName" label="类型">

                            </el-table-column>
                            <el-table-column prop="disabled" label="状态">
                                <template #default="scoped">
                                    <el-switch v-model="scoped.row.disabled" @change="changeStatus(scoped.row,'courseAttributesList',scoped.$index)"/>
                                </template>
                            </el-table-column>
                            <el-table-column label="操作" fixed="right" width="120">
                                <template #default="scoped">
                                    <el-button type="success" plain size="small" @click="editCustomAttr(scoped.row)">
                                        编辑
                                    </el-button>
                                </template> 
                            </el-table-column>
                        </el-table>
                    </div>
                    <div style="width:100%;margin-bottom:24px">
                        <div class="lis-head">
                            <div class="icon-view">
                                <div class="icon-view-on"></div>
                            </div>
                            <span class="label-name">物资自定义属性</span>
                            <el-button plain type="primary" @click="addCustomAttr(4)">
                                <img src="@/assets/icon/btn-add-blue.png" alt="" style="margin-right:8px;width:14px;height:14px">
                                添加属性
                            </el-button>
                        </div>
                        <el-table :data="customData.goodsAttributesList" style="width: 100%" stripe>
                            <el-table-column prop="fieldName" label="属性名称">
                            </el-table-column>
                            <el-table-column prop="fieldTypeName" label="类型">

                            </el-table-column>
                            <el-table-column prop="disabled" label="状态">
                                <template #default="scoped">
                                    <el-switch v-model="scoped.row.disabled" @change="changeStatus(scoped.row,'goodsAttributesList',scoped.$index)"/>
                                </template>
                            </el-table-column>
                            <el-table-column label="操作" fixed="right" width="120">
                                <template #default="scoped">
                                    <el-button type="success" plain size="small" @click="editCustomAttr(scoped.row)">
                                        编辑
                                    </el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                    </div>
                </div>

            </el-tab-pane>
            <!-- <el-tab-pane label="诊断设置" name="diagnosticSetting">
                <div class="tab-diag">
                    <dia-setting v-if="activeName == 'diagnosticSetting'"></dia-setting>
                </div>
            </el-tab-pane> -->
        </el-tabs>
        <el-dialog v-model="attrFlag" :title="attrTitle" width="380px">
            <div v-loading="attrLoading" style="width:100%;max-height:500px;overflow:auto" v-if="attrFlag">
                <template  v-for="(item,index) in attrList" :key="index">
                    <div class="input-line">
                        <el-input v-model.trim="item.value" placeholder="请输入" @blur="handleAttrBlur(index)" style="width:250px;margin-right: 8px;" :maxlength="50"/>
                        <el-switch v-model="item.delFlag" :active-value="0" :inactive-value="1" />
                        <img src="@/assets/icon/incre-icon.png" alt="" @click="increHandle()" v-if="attrList.length<100">
                        <img src="@/assets/icon/diff-icon.png" alt="" @click="diffHandle(index)" v-if="!item.id">
                    </div>  
                </template>
            </div>
            <template #footer>
                <div class="dialog-footer">
                    <el-button :loading="attrLoading" @click="attrFlag = false">取消</el-button>
                    <el-button type="primary" @click="confrimAttr()" :loading="attrLoading">确定</el-button>
                </div>
            </template>
        </el-dialog>
        <el-dialog v-model="attrCustomFlag" :title="`${ attrCustomForm.id?'编辑':'添加' }自定义属性`" width="380px">
            <div style="width:100%;box-sizing:border-box;max-height:500px;overflow:auto" v-if="attrCustomFlag">
                <el-form :model="attrCustomForm" label-width="80px" :rules="rules" ref="attrCustomFormRef">
                    <el-form-item label="属性类型" :rules="getRules('select', '属性类型')" prop="type">
                        <el-radio-group v-model="attrCustomForm.type" class="ml-4" :disabled="!!attrCustomForm.id">
                            <el-radio :label="1">文本</el-radio>
                            <el-radio :label="2">数值</el-radio>
                            <el-radio :label="3">选项</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="属性名称" :rules="getRules('input', '属性名称')" prop="name">
                        <el-input v-model="attrCustomForm.name" placeholder="请输入" style="width:100%" :maxlength="20"/>

                    </el-form-item>
                    <el-form-item label="选项类型" :rules="getRules('select', '选项类型')" prop="selectType" v-if="attrCustomForm.type == 3">
                        <el-radio-group v-model="attrCustomForm.selectType" class="ml-4" :disabled="!!attrCustomForm.id">
                            <el-radio :label="1">单选</el-radio>
                            <el-radio :label="2">多选</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="选项内容" required v-if="attrCustomForm.type == 3">
                        <template  v-for="(item,index) in attrCustomForm.selectValue" :key="index">
                            <div class="input-line">
            
                                <el-input v-model.trim="item.value" placeholder="请输入" style="width:220px" :maxlength="50" @blur="checkRepeat(index,item.value)"/>
                                <img src="@/assets/icon/incre-icon.png" alt="" @click="increCustomHandle()" v-if="attrCustomForm.selectValue.length<50">
                                <img src="@/assets/icon/diff-icon.png" alt="" @click="diffCustomHandle(index)" v-if="(attrCustomForm.selectValue.length>1)">
                            </div>  
                        </template>
                    </el-form-item>
                </el-form>
            </div>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="attrCustomFlag = false">取消</el-button>
                    <el-button type="primary" @click="confrimCustomAttr()" :loading="insertCustomLoading">确定</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>
<style lang="less" scoped>
.input-line{
    width: 100%;
    display: flex;
    justify-content: flex-start;
    align-items: center;
    margin-bottom:16px;

    img{
        cursor: pointer;
        width: 16px;
        height: 16px;
        margin-left:8px;
    }
}

.page-contain{
    width: 100%;
    height: 100%;
    .tab-pag{
        width: 100%;
        height: 100%;
        box-sizing: border-box;
        padding:8px 24px;
        overflow: auto;
    }
    .tab-diag{
        width: 100%;
        height: 100%;
        box-sizing: border-box;
        padding:2px 12px;
        overflow: auto;
    }
    .lis-head{
        width: 100%;
        display: flex;
        justify-content: flex-start;
        align-items: center;
        padding-bottom:8px;
        .icon-view{
            margin-right: 8px;
            position: relative;
            width: 14px;
            height: 14px;

            &::before {
                content: "";
                position: absolute;
                top: 0;
                left: 0;
                width: 10px;
                height: 10px;
                border-radius: 2px;
                background-color: #10E7F9; 
            }
            .icon-view-on{
                position: absolute;
                bottom: 0;
                right: 0;
                width: 10px;
                height: 10px;
                border-radius: 2px;
                background-color: #3480FF; /* 背景色 */
            }
        }
        .label-name{
            color: #000000;
            font-weight: bold;
            font-size: 14px;
            margin-right: 8px;
        }
        img{
            width: 14px;
            height: 14px;
            cursor: pointer;
        }
    }
    :deep(.el-table__row){
        .el-input .el-input__wrapper{
            background: rgba(0,0,0,0);
        }
    }
  
}
</style>